﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Reflection;
using System.IO;
using Shop.Crawler.IRobot;
using Shop.Crawler.PluginAttribute;

namespace Shop.Crawler.PluginCore
{
    public class HostProvider
    {
        private static List<RobotNet> _robots;
        public static List<RobotNet> Robots
        {
            get
            {
                if (null == _robots)
                    Reload();

                return _robots;
            }
        }

        public static void Reload()
        {
            if (null == _robots)
                _robots = new List<RobotNet>();
            else
                _robots.Clear();

            _robots.Add(new RobotNet());
            List<Assembly> pluginAssemblies = LoadPluginAssembly();
            List<IRobotNet> plugins = GetPlugins(pluginAssemblies);

            foreach (IRobotNet calc in plugins)
                _robots.Add(new RobotNet(calc));
        }

        private static List<Assembly> LoadPluginAssembly()
        {
            DirectoryInfo dInfo = new DirectoryInfo(Path.Combine(Environment.CurrentDirectory, "Plugins"));
            List<Assembly> pluginAssemblyList = new List<Assembly>();
            FileInfo[] files = dInfo.GetFiles("*.dll");
            if (null != files)
            {
                foreach (FileInfo file in files)
                    pluginAssemblyList.Add(Assembly.LoadFile(file.FullName));
            }

            return pluginAssemblyList;
        }

        static List<IRobotNet> GetPlugins(List<Assembly> assemblies)
        {
            List<Type> availableTypes = new List<Type>();
            foreach (Assembly assembly in assemblies)
                availableTypes.AddRange(assembly.GetTypes());

            List<Type> calculatorList = availableTypes.FindAll(delegate(Type t)
            {
                List<Type> interfaceTypes = new List<Type>(t.GetInterfaces());
                object[] arr = t.GetCustomAttributes(typeof(RobotPluginAttribute), true);
                return !(arr == null || arr.Length == 0) && interfaceTypes.Contains(typeof(IRobotNet));
            });

            return calculatorList.ConvertAll<IRobotNet>(delegate(Type t) { return Activator.CreateInstance(t) as IRobotNet; });
        }
    }
}
